bent.bash

#!/usr/bin/env bash

dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
codeDir=$dir
IMPORTS=()

function source_files(){
    # . $codeDir/aliases.bash
    . $codeDir/internal/os-setup.bash

    . $codeDir/internal/colors.bash
    . $codeDir/internal/color-vars.bash
    . $codeDir/internal/unsorted.bash
    . $codeDir/internal/branch.bash
    . $codeDir/internal/url.bash
    . $codeDir/internal/files.bash
    . $codeDir/internal/msg.bash
    . $codeDir/internal/prompt.bash
    . $codeDir/internal/strings.bash
    # . $codeDir/internal/build-command.bash

}

function import(){
    imp="${1/\//-}"
    existing=${IMPORTS["$imp"]}
    if [[ "$existing" != "$imp" ]];then
        file="${codeDir}/${1}.bash"
        if [[ -f "$file" ]];then
            source "$file"
        fi
        IMPORTS["$imp"]="$imp"
    fi
}

function is_function(){
    func="$1";
    TYPE=`LC_ALL=C type -t "${func}"`;
    if [[ -n $TYPE && $TYPE == 'function' ]]; then
        return 0;
    fi

    return 1;
}

function run(){
    # Determine the command group
    # msg_header "Try"
    # echo ":::${@}"
    cmd_group="$1";
    cmd_group_file="${codeDir}/core/${cmd_group}.bash"
    input=("${@:2}")
    
    # Check if command group's file exists, else set to core
    if [[ ! -f "${cmd_group_file}" ]]; then
        input=("${@:1}")
        cmd_group="core"
        # cmd_group_file="${codeDir}/core/${cmd_group}.bash"
    fi
    import "core/${cmd_group}"
    # echo "FILE: ${cmd_group_file}"

    ## Preparing the command
    testCommand="${@:1}";
    # echo "Test: $testCommand"
    len="${#@}"
    args="${@}"
    while [[ $len -ge 1 ]]; do
        testCommand="${@:1:$len}"
        testCommand="${testCommand// /_}"
        if is_function "$testCommand";then
            cmd="$testCommand"
            hits=$tries
            args="${@:$((len+1))}"
            break;
        fi

        len=$(( len - 1 ))
    done

    if [[ -z "${cmd}" ]];then
        # echo "TRYING core_"
        ## Preparing the command
        testCommand="${@:1}";
        len="${#@}"
        args="${@}"
        while [[ $len -ge 1 ]]; do
            testCommand="${@:1:$len}"
            testCommand="${testCommand// /_}"
            testCommand="core_${testCommand}"
            if is_function "$testCommand";then
                cmd="$testCommand"
                hits=$tries
                args="${@:$((len+1))}"
                break;
            fi

            len=$(( len - 1 ))
        done
    fi

    if [[ -z "${cmd}" ]];then
        msg "${cMistake}[bent ${@:1:1}] is not a command${cOff}"
        msg
        run "help"
    else
        # msg_header "[bent ${cmd}]${cOff} ${args[@]}"
        $cmd ${args[@]}
    fi
}


source_files

# Provide clear starting point for bent output
line_break;

# run core upload
run $@

msg ""